<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\BaseController;
use App\Models\Cart;
use App\Models\Good;
use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class OrderController extends BaseController
{
    /**
     * 订单预览页
     */
    public function preview(Request $request)
    {
        //地址数据
        // TODO 模拟地址数据
        $address = [
            [
                'id'      => 1,
                'name'    => '张三',
                'phone'   => '12345678901',
                'address' => '广东省深圳市南山区',
            ],
            [
                'id'      => 2,
                'name'    => '李四',
                'phone'   => '12345678901',
                'address' => '广东省深圳市南山区',
            ],
            [
                'id'      => 3,
                'name'    => '王五',
                'phone'   => '12345678901',
                'address' => '广东省深圳市南山区',
            ],
        ];

        //购物车数据
        $carts = Cart::where('user_id', $request->user()->id)
                     ->where('is_checked', 1)
                     ->with('goods:id,title,price,cover')
                     ->get();

        //返回数据
        return $this->response->array([
                                          'address' => $address,
                                          'carts'   => $carts,
                                      ]);
    }

    /**
     * 提交订单
     */
    public function store(Request $request)
    {
        $request->validate(
            [
                'address_id' => 'required' //TODO 地址要存在才行 exists:address,id
            ],
            [
                'address_id.required' => '收货地址不能为空',
            ]
        );

        //处理插入的数据
        $user_id = auth('api')->id();
        $order_no = date('YmdHis') . rand(100000, 999999);
        $amount = 0;
        $cartsQuery = Cart::where('user_id', $user_id)
                          ->where('is_checked', 1)
                          ->with('goods:id,price,stock,title');

        $carts = $cartsQuery->get();

        //判断购物车是否为空
        if ($carts->isEmpty()) {
            return $this->response->errorBadRequest('购物车为空');
        }

        //要插入的订单详情数据
        $insertData = [];


        foreach ($carts as $cart) {
            //如果有商品库存不足，提示用户重新选择
            if ($cart->goods->stock > $cart->num){
                return $this->response->errorBadRequest($cart->goods->title.' 库存不足，请重新选择商品');
            }
            $insertData[] = [
                'goods_id' => $cart->goods->id,
                'price'    => $cart->goods->price,
                'num'      => $cart->num,
            ];
            $amount += $cart->goods->price * $cart->num;
        }

        try {

            //生成订单
            $order = Order::create(
                [
                    'user_id'    => $user_id,
                    'order_no'   => $order_no,
                    'amount'     => $amount,
                    'address_id' => $request->input('address_id'),
                ]
            );
            //生成订单详情
            $order->orderDetails()->createMany($insertData);

            //清空购物车
            $cartsQuery->delete();

            //减去商品对应的库存
            foreach ($carts as $cart){
                Good::where('id',$cart->goods->id)->decrement('stock',$cart->num);
            }

            DB::commit();
            return $this->response->created();
        } catch (\Exception $e) {
            DB::rollBack();
            throw $e;
        }
    }
}
